home *** CD-ROM | disk | FTP | other *** search
- Path: hopper.acm.org!news
- From: varnk@e62.diebold.com (Ken Varn)
- Newsgroups: comp.lang.c
- Subject: Re: array of struct
- Date: 22 Mar 1996 13:33:12 GMT
- Organization: Diebold
- Message-ID: <4iua6o$ftq@hopper.acm.org>
- References: <Pine.LNX.3.91.960319173746.16221A-100000@larry.inf.net>
- NNTP-Posting-Host: 199.218.232.47
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.7
-
- In article <Pine.LNX.3.91.960319173746.16221A-100000@larry.inf.net>,
- larry@larry.inf.net says...
- >
- >
- >I have a question... though it is petty it bothers me greatly. :(
- >
- >How would I create a runtime defined array of struct.
- >
- >What I want to do is create each record in the array by reading a line
- >from a file and storing each field of the line into the record. Do this
- >for every line in the file and then where done. What I need to do is
- >create the array of the struct for the exact number of lines that are in
- >the file. This way I won't be wasting memory and I won't have to worry
- >about not having enough records to store the lines into.
- >
-
- You need to use dynamic allocation with malloc() or calloc(). See below.
-
-
- typedef struct {
- int var;
- /* whatever else you want in structure. */
- } StructureName;
-
-
- void main(void)
-
- {
- StructureName *Structure;
- int NumRecs = 10;
-
- Structure = malloc(NumRecs,sizeof(*Structure));
-
- if (Structure == NULL)
- printf("Allocation Failed");
- else
- {
- /* Access structure anyway you want here with array subscripting */
- /* i.e. Structure[0].var = x;
- }
- }
-
-
-